/**
 * 
 */
package info.niwota.search;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.repackaged.org.json.JSONObject;

/**
 * @author qiangli
 * 
 */
@SuppressWarnings("serial")
public class JSONPServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(JSONPServlet.class
			.getName());

	private boolean isEmpty(String s) {
		return (s == null || s.equals(""));
	}

	protected void sendJSON(HttpServletRequest req, HttpServletResponse res,
			JSONObject data) throws IOException {
		
		log.info("sendJSON uri: "+ req.getRequestURI());
		
		res.setContentType("application/json");
		PrintWriter out = res.getWriter();

		String callback = req.getParameter("callback");
		String js = null;
		if (isEmpty(callback)) {
			js = data.toString();
		} else {
			js = callback + "(" + data.toString() + ")";
		}
		out.println(js);

		log.fine("json: " + js);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			handle(req, resp);
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			handle(req, resp);
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}
	}

	private void handle(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		final String uri = req.getRequestURI();

		if (uri.startsWith("/jsonp/crypto")) {
			HttpSession session = req.getSession(true);
			String[] key = (String[]) session.getAttribute("public.key");
			if (key == null) {
				KeyPair kp = CryptUtils.generateKeyPair();
				key = CryptUtils.toPublicKey(kp);
				session.setAttribute("public.keypair", kp);
				session.setAttribute("public.key", key);
			}
			JSONObject data = new JSONObject();
			data.put("modulus", key[0]);
			data.put("exponent", key[1]);
			sendJSON(req, resp, data);
			return;
		}
	}
}
